package com.ccdc.lbcmsystem.controller;

import com.ccdc.lbcmsystem.mapper.*;
import com.ccdc.lbcmsystem.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Controller
@Slf4j
public class IndexController {
    @Autowired
    JavaMailSenderImpl mailSender;

    @Autowired
    FeedBackMapper feedBackMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ChildrenMapper childrenMapper;

    @Autowired
    VeteranMapper veteranMapper;

    @Autowired
    ElderlyMapper elderlyMapper;

    @Autowired
    NoticeMapper noticeMapper;

    @Autowired
    ExamineMapper examineMapper;

    @Autowired
    GiftMapper giftMapper;


    @RequestMapping({"/toLogin", "/"})
    public String toLogin() {
        return "login";
    }

    @RequestMapping({"/login"})
    @ResponseBody
    public String login(String username, String password, String role, HttpSession session) {
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        User user = userMapper.queryUserByUserName(username);
        log.info("----------------------执行登录");
        String msg = "";
        if (user!=null && user.getStatus().equals("1") && user.getExamineStatus().equals("1") && !user.getCancellationStatus().equals("0")){
            String role1 = user.getRole();
            session.setAttribute("role", role1);
            String name = user.getName();
            session.setAttribute("name", name);
            String examineStatus = "0";
            int examineStatusSize = userMapper.queryListUserByExamineStatus(examineStatus).size();
            session.setAttribute("examineStatusSize",examineStatusSize);
            int DelChildrenSize = examineMapper.queryDelChildrenList().size();
            session.setAttribute("DelChildrenSize",DelChildrenSize);
            if (role1.equals("0")){
                String role3 = "1";
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUsers(role3, cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("1")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("2")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("3")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("4")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("5")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("6")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            if (role1.equals("7")){
                String cancellationStatus = "0";
                int cancellationSize = examineMapper.queryCancelExamineUser(cancellationStatus).size();
                session.setAttribute("cancellationSize",cancellationSize);
            }
            System.out.println(role+role1);
            try {
                if (role1.equals(role)) {//用户名角色和选择的角色一致
                    subject.login(token);
                    String username1 = token.getUsername();
                    System.out.println(username1+username);
                    session.setAttribute("username", username1);
                    msg = "OK";
                    System.out.println(msg);
                    return msg;
                }
                else {
                    msg = "角色与用户名不匹配";
                    log.info("----------------------"+msg);
                    return msg;
                }

            } catch (UnknownAccountException e) {
            /*model.addAttribute("msg","用户名或密码错误");
            System.out.println("用户名错误");*/
                msg = "用户名输入错误";
                log.info("----------------------"+msg);
                return msg;
            } catch (IncorrectCredentialsException e) {
            /*model.addAttribute("msg","用户名或密码错误");
            System.out.println("密码错误");*/
                msg = "密码输入错误";
                log.info("----------------------"+msg);
                return msg;
            }
        }
        else if (user!=null && user.getExamineStatus().equals("0")){
            msg = "账号审核中,请耐心等待";
            log.info("----------------------"+msg);
            return msg;
        }
        else if (user!=null && user.getExamineStatus().equals("2")){
            msg = "账号审核未通过，禁止登陆";
            log.info("----------------------"+msg);
            return msg;
        }
        else if (user!=null && user.getCancellationStatus().equals("0")){
            msg = "账号处于注销审核状态，禁止登陆";
            log.info("----------------------"+msg);
            return msg;
        }
        else {
            msg = "用户不存在";
            log.info("----------------------"+msg);
            return msg;
        }

    }

    @RequestMapping("/logout")
    public String logout() {
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }

    @RequestMapping("/index")
    public String index(Model model) {
        Notice notice = noticeMapper.queryStatus();
        List<Children> children = childrenMapper.queryChildrenList();
        model.addAttribute("ChildrenNum",children.size());//留守儿童数量
        List<User> community = userMapper.queryCommunityList();
        model.addAttribute("CommunityNum",community.size());//工作人员用户数量
        List<User> users = userMapper.queryUserList();
        model.addAttribute("ManagerNum",users.size());
        List<Veteran> veterans = veteranMapper.queryVeteranList();
        model.addAttribute("VeteranNum",veterans.size());//退伍军人数量
        List<Elderly> elderlies = elderlyMapper.queryElderlyList();
        model.addAttribute("ElderlyNum",elderlies.size());//独居老人数量
        List<Gift> gifts = giftMapper.queryGiftList();
        model.addAttribute("GiftsNum",gifts.size());//独居老人数量
        if (notice==null){
            String theme = "暂无公告";
            model.addAttribute("theme",theme);
        }else {
            String theme = notice.getTheme();
            String content = notice.getContent();
            model.addAttribute("theme",theme);
            model.addAttribute("content",content);
        }
        return "index";
    }

    @RequestMapping("/toForget")
    public String toForget(){
        return "forget";
    }

    @RequestMapping("/forget")
    @ResponseBody
    public String forget(String username,String protocol,String host) throws MessagingException {
        String msg = "OK";
        String from = "1245996419@qq.com";
        String nickName = "'关爱'信息管理系统";
        //发送邮件给管理员提醒初始化密码
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setSubject("系统通知");
        helper.setText("亲爱的管理员您好，您收到了"+username+"的账号密码初始化申请，请及时将该用户密码初始化。"+"<a href="+protocol+"//"+host+">点击前往</a>",true);
        helper.setTo("1245996419@qq.com");
        helper.setFrom(nickName+'<'+from+'>');
        mailSender.send(mimeMessage);
        return msg;

    }

    @RequestMapping("/toReg")
    public String toReg() {
        return "reg";
    }

    @RequestMapping("/reg")
    @ResponseBody
    public String reg(String name,String username,String password,String password2,
                      String email,String tel,String role,String host,String protocol) throws MessagingException {
        String msg = "";
        User user1 = userMapper.queryUserByUserName(username);
        if (username.equals("")){
            msg = "请输入用户名";
            return msg;
        }
        if (name.equals("")){
            msg = "请输入姓名";
            return msg;
        }
        if (password.equals("")){
            msg = "请输入密码";
            return msg;
        }
        if (password2.equals("")){
            msg = "请输入确认密码";
            return msg;
        }
        if (email.equals("")){
            msg = "请输入邮箱";
            return msg;
        }
        if (tel.equals("")){
            msg = "请输入电话号码";
            return msg;
        }
        if (user1 != null && !username.equals("")){
            msg = "用户名已存在,请重新输入";
            return msg;
        }
        if (!password.equals("") && !password2.equals("") && !password.equals(password2)){
            msg = "两次密码不一致,请重新输入";
            return msg;
        }
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(regEx1);
        Matcher m = p.matcher(email);
        if (!m.matches() && !email.equals("")){
            msg = "邮箱格式错误,请重新输入";
            return msg;
        }
        String REG_EXP = "^([0-9]{3}-?[0-9]{8}|[0-9]{4}-?[0-9]{7})$";
        if (!tel.matches(REG_EXP) && !tel.equals("")){
            msg = "手机号码错误,请重新输入";
            return msg;
        }
        else {
            msg = "OK";
            User user = new User();
            user.setName(name);
            user.setUserName(username);
            user.setPassWord(password);
            user.setRole(role);
            user.setEmail(email);
            user.setTel(tel);
            SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date createTime = new Date();
            String time = sft.format(createTime);
            user.setCreateTime(time);
            String examineStatus = "0";
            user.setExamineStatus(examineStatus);
            userMapper.addUser(user);

            SimpleMailMessage message = new SimpleMailMessage();
            message.setSubject("系统通知");
            message.setText("您好！我们已经收到您的账号注册申请，我们会尽快处理，审核结果会发送到您的邮箱，请注意查收。");
            String from = "1245996419@qq.com";
            String nickName = "'关爱'信息管理系统";
            message.setTo(email);
            message.setFrom(nickName+'<'+from+'>');
            mailSender.send(message);
            //发送邮件给管理员提醒审核
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setSubject("系统通知");
            helper.setText("亲爱的管理员您好，您收到了新的账号注册申请，请及时审核。"+"<a href="+protocol+"//"+host+">点击前往</a>",true);
            helper.setTo("1245996419@qq.com");
            helper.setFrom(nickName+'<'+from+'>');
            mailSender.send(mimeMessage);
            return msg;
        }
    }
    //跳转修改密码页面
    @RequestMapping("/toEditPwd/{username}")
    public String toEditPwd(@PathVariable("username") String username,Model model) {
        User user = userMapper.queryUserByUserName(username);
        model.addAttribute("user",user);
        return "editPwd";
    }
    @RequestMapping("/editPwd")
    @ResponseBody
    public String editPwd(Integer id,String oldPwd,String newPwd,String confirmPwd){
        String msg = "";
        User user = userMapper.queryUserById(id);
        try {
            String passWord = newPwd;
            userMapper.updateUserPwdById(id,passWord);
            msg = "OK";
            return msg;
        }catch (Exception e){
            msg = "修改失败";
            return msg;
        }
    }
    //个人中心
    @RequestMapping("/userInfo/{username}")
    public String userInfo(@PathVariable("username") String username,Model model){
        User user = userMapper.queryUserByUserName(username);
        model.addAttribute("user",user);
        return "userInfo";
    }

    @RequestMapping("/userEdit")
    @ResponseBody
    public String userEdit(Integer id,String name,String email,String tel){
        String msg = "";
        try {
            userMapper.editUser(id,name,tel,email);
            msg = "OK";
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg = "操作失败";
            return msg;
        }
    }
    //账号注销
    @RequestMapping("/cancellation")
    @ResponseBody
    public String cancellation(Integer id){
        String msg = "";
        try {
            String cancellationStatus = "0";
            userMapper.cancellationUser(id,cancellationStatus);
            msg = "OK";
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg = "操作失败";
            return msg;
        }
    }
}
